<template>
    <div>
        <el-dialog center class="global-dialog" v-model="dialogVisable" width="60%" top="10vh" :show-close="true"
            :close-on-click-modal="false" @close="close">
            <template #title>
                <div class="my-header"  v-loading="detail_loading">
                    <el-tabs v-model="tabId" class="demo-tabs">
                        <el-tab-pane label="基本信息" name="1">
                            <el-form :model="diaForm" ref="DiaForm" :rules="rules" status-icon label-width="110px" status>
                                <el-row :gutter="20">
                                    <el-col :span="12">
                                        <el-form-item label="论文题目" prop="title">
                                            <el-input placeholder="请输入" v-model="diaForm.title" style="width: 100%"  maxlength="50" show-word-limit clearable />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="期刊名称" prop="magazineName">
                                            <el-input placeholder="请输入" v-model="diaForm.magazineName"
                                                style="width: 100%"  maxlength="50" show-word-limit clearable />
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row :gutter="20">
                                    <el-col :span="12">
                                        <el-form-item label="论文级别" prop="levelId">
                                            <el-select clearable v-model="diaForm.levelId" placeholder="论文级别"
                                                @change="changeLevel" style="width: 100%">
                                                <el-option :label="item.itemText" :value="item.itemValue"
                                                    :key="item.itemValue" v-for="item in levelList" />
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="期刊号" prop="magazineNo">
                                            <el-input placeholder="请输入" v-model="diaForm.magazineNo" style="width: 100%" maxlength="20" show-word-limit clearable />
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row :gutter="20">
                                    <el-col :span="12">
<!--                                        <el-form-item label="所属项目" prop="projectId">
                                            <el-select v-model="diaForm.projectId" placeholder="请选择" style="width: 100%"
                                                @change="changeProject" filterable>
                                                <el-option :label="item.projectname" :value="item.id" :key="item.id"
                                                    v-for="item in projectList" />
                                            </el-select>
                                        </el-form-item>-->
                                      <el-form-item label="所属项目" prop="project">
                                        <el-select v-model="diaForm.project" filterable placeholder="请选择" style="width: 80%"
                                                   @change="changeProject"  clearable disabled >
                                          <el-option :label="item.projectname" :value="item.id" :key="item.id"
                                                     v-for="item in projectList"  />

                                        </el-select>
                                        <el-button type="primary" @click="open">选择</el-button>
                                      </el-form-item>
                                      <template #append>

                                      </template>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="发表日期" prop="publicDate">
                                            <el-date-picker type="date" placeholder="选择日期" v-model="diaForm.publicDate"
                                                value-format="YYYY-MM-DD" style="width: 100%" clearable ></el-date-picker>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row :gutter="20">
                                    <el-col :span="12">
                                        <el-form-item label="业务板块" prop="techClassId">
                                            <el-select clearable v-model="diaForm.techClassId" placeholder="请选择"
                                                @change="changeTechClass" style="width: 100%">
                                                <el-option :label="item.itemText" :value="item.itemValue"
                                                    :key="item.itemValue" v-for="item in techClassList" />
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="维护单位" prop="maintainUnit">

                                            <popup-tree-input  :data="orgAllList" :props="popupTreeProps" :prop="deptForm.parentName == null
                                                ? $t('message.org.top_menu')
                                                : diaForm.maintainUnit
                                                " :node-key="'' + deptForm.parentId"
                                                :current-change-handle="changeUnit" />
                                        </el-form-item>
                                    </el-col>
                                </el-row>

                                <el-row :gutter="20">
                                    <el-col :span="12">
                                        <el-form-item label="企业排名" prop="enterpriseRanking">
                                            <el-select v-model="diaForm.enterpriseRanking" placeholder="请选择"
                                                style="width: 100%" clearable>
                                                <el-option :label="item.itemText" :value="item.itemValue"
                                                    :key="item.itemValue" v-for="item in RankingList" />
                                            </el-select>
                                        </el-form-item>
                                    </el-col>

                                    <el-col :span="12">
                                        <el-form-item label="语言" prop="languageId">
                                            <el-select v-model="diaForm.languageId" placeholder="请选择" style="width: 100%"
                                                @change="changeLange" clearable>
                                                <el-option :label="item.itemText" :value="item.itemValue"
                                                    :key="item.itemValue" v-for="item in languageList" />
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                </el-row>

                                <el-row :gutter="20">
                                    <!-- <el-col :span="12">
                                        <el-form-item label="字数" prop="wordCount">
                                            <el-input oninput="value=value.replace(/^0|[^0-9]/g,'')" type="number"
                                                placeholder="请输入" v-model="diaForm.wordCount" style="width: 100%" />
                                        </el-form-item>
                                    </el-col> -->
                                    <el-col :span="12">
                                        <el-form-item label="影响因子" prop="yxyz">
                                            <el-input @input="diaForm.yxyz=diaForm.yxyz.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')"
                                                placeholder="请输入" v-model="diaForm.yxyz" style="width: 100%"  maxlength="8" clearable
                                            />
                                        </el-form-item>
                                    </el-col>
                                  <el-col :span="12">

                                    <el-form-item label="合同中规定的成果" prop="isContractSuccess" label-width="90">
                                      <el-select
                                          v-model="diaForm.isContractSuccess"
                                          placeholder="请选择"
                                          style="width: 100%">
                                        <el-option
                                            :label="item.text"
                                            :value="item.value"
                                            :key="item.value"
                                            v-for="item in options.isHightPayList"
                                        />
                                      </el-select>
                                    </el-form-item>
                                  </el-col>
                                </el-row>

                                <el-form-item label="关键词" prop="keyword">
                                    <el-input v-model="diaForm.keyword" :autosize="{ minRows: 2, maxRows: 6 }"
                                        type="textarea" placeholder="请输入" maxlength="300" show-word-limit clearable />
                                </el-form-item>

                                <el-form-item label="说明" prop="illustrate">
                                    <el-input v-model="diaForm.illustrate" :autosize="{ minRows: 2, maxRows: 6 }"
                                        type="textarea" placeholder="请输入" maxlength="300" show-word-limit clearable />
                                </el-form-item>
                            </el-form>
                        </el-tab-pane>
                        <el-tab-pane label="参编单位" name="2">
                            <UnitMembers v-if="dialogVisable" :members="unitList" :membersFlag="unitFlag" @paramsChange="changeUnitInfo">
                            </UnitMembers>
                        </el-tab-pane>
                        <el-tab-pane label="参编人员" name="3">
                            <PeopelMembers v-if="dialogVisable" :members="memberList" :membersFlag="memberFlag" @paramsChange="changePeopleInfo">
                            </PeopelMembers>
                        </el-tab-pane>
                        <el-tab-pane label="相关附件" name="4">
                            <PlatformFiles v-if="dialogVisable"  :files="files" @filesParams="filesParams"   download="KJSL:KJCG:XSLW:DOWNLOAD"  upload="KJSL:KJCG:XSLW:UPLOAD" fileDelete="KJSL:KJCG:XSLW:FILEDELET"></PlatformFiles>
                        </el-tab-pane>
                        <el-tab-pane label="变更记录" name="5" >
                            <Record v-if="id" :changeLogs="changeLogs"></Record>
                        </el-tab-pane>
                    </el-tabs>
                </div>
            </template>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="close">关闭</el-button>
                    <el-button type="primary" @click="save">保存</el-button>
                </span>
            </template>
        </el-dialog>
    </div>

  <!-- 项目弹窗 -->
  <el-dialog v-model="Visible" width="900px" top="17vh" :show-close="false" :close-on-click-modal="false">
    <template #title>
      <div class="my-header">
        <el-tabs v-model="activeName" class="demo-tabs">
          <el-tab-pane label="项目选择" name="first">
            <div class="search-box">
              <el-input v-model="xiangmuParams.projectName" placeholder="请输入" class="input-with-select"
                        style="width: 300px">
                <template #append>
                  <el-button type="primary" @click="open">搜索</el-button>
                </template>
              </el-input>
            </div>
            <el-table :data="options.xiangmuList" style="width: 100%" border @selection-change="handleSelectionChange1">
              <el-table-column type="selection" width="40" />
              <el-table-column prop="projectName" label="项目名称" />
              <el-table-column prop="projectNumber" label="项目编号" />
              <el-table-column prop="departmentName" label="关联部门" />
              <el-table-column prop="projectLeaderName" label="项目负责人" />
              <el-table-column prop="projectYear" label="立项年份" />
            </el-table>
            <div class="example-pagination-block">
              <el-pagination
                  background
                  layout="prev, pager, next ,total,sizes,jumper"
                  :total="options.total"
                  :page-size="xiangmuParams.size"
                  @current-change="handleCurrentChange"
                  @size-change="handleSizeChange"
              />
            </div>
          </el-tab-pane>
        </el-tabs>
        <div class="handle">
          <el-button color="#626aef" @click="Visible = false">关闭</el-button>
          <el-button type="primary" @click="toHandle1">关联</el-button>
        </div>
      </div>
    </template>
  </el-dialog>

</template>

<script>
import {
addForm,
editForm,
getDetailById,
getDictionary,
getProject,
getUnit,
} from "@/views/science/api/thesis";
import PopupTreeInput from '@/views/science/components/PopupTreeInput/index.vue';
import PlatformFiles from "@/views/science/components/platformFiles/platformFiles.vue";
import Record from "@/views/science/components/record/record.vue";
import { tips } from "@/views/science/components/tips/tips";
import { onMounted, reactive, ref, toRefs, watch } from "vue";
import PeopelMembers from "./PeopelMembers.vue";
import UnitMembers from "./UnitMembers.vue";
import {projectManagementListPage} from "@/views/science/technologyStrength/api/technologyStrength";
import Api from "@/views/science/api/profess";

export default {
    components: {
        PlatformFiles,
        Record,
        UnitMembers,
        PeopelMembers,
        PopupTreeInput
    },
    props: {

        orgAllList: {
            type: Array,
            required: true,
        },
        dialogVisable: {
            type: Boolean,
            default: false,
        },

        // falg  1:新增  2:编辑  3:详情
        flag: {
            type: String,
            default: 1,
        },
        id: {
            type: String,
            default: "",
        },

    },
    setup(props, { emit }) {
        watch(
            () => props.dialogVisable,

            () => {
                // 深度监听.只有在id存在的时候调用详情的接口
                if (props.id) {
                    getDetail(props.id);
                }
            },

            { deep: true, immediate: true }
        );
        // 发送请求
        onMounted(() => {


            // 获取数据字典

            getCodeList();

            getUnitList();

            getProjectList();
        });

        const deptForm = {
            parentId: 0,
            parentName: '',
        }

        let DiaForm = ref();
        let data = reactive({
            popupTreeProps: {
                label: 'name',
                children: 'children',
            },

            tabId: "1",
            detail_loading:false,
            levelList: [],
            workAttributeList: [],
            techClassList: [],
            languageList: [],
            RankingList: [],
            unitNameList: [],

            projectList: [], //项目

            memberList: [],
            unitList: [],

            unitFlag: false,
            memberFlag: false,

            diaForm: {
                id: "",
                title: "",
                magazineName: "",
                magazineNo: "",
                level: "",
                levelId: "",
                projectId: "",
                project: "",
                techClassId: "",
                techClass: "",
                projectName: "",
                maintainUnitId: "",
                maintainUnit: "",
                enterpriseRanking: "",
                languageId: "",
                language: "",
                illustrate: "",
                yxyz: "",
              isContractSuccess: '',
            },

            files: [],

            changeLogs: [],
        });
      //清空form
      const clearForm = () =>{
        data.diaForm.isContractSuccess = ''

      }
      // 弹窗中的选择
      let options = reactive({
        xiangmuList: [], //项目列表
        projectList: [],
        contractList: [],
        total:0,
        isHightPayList:[
          {text:'否',value:'1',},
          {text:'是',value:'0',},
        ],
      })
      let Visible = ref(false)
      //项目搜索参数
      let xiangmuParams = reactive({
        projectName: '',
        projectNumber: '',
        createOrgId: '',
        level: '',
        current: 1,
        size: 10,
        projectCategory: '1',
      })
      //项目列表
      let open = async () => {
        const res = await projectManagementListPage(xiangmuParams)
        const rs = res.data.data
        options.xiangmuList = rs.records
        options.total = rs.total
        Visible.value = true
      }
      //改变页码
      const handleCurrentChange = (e) => {
        xiangmuParams.current = e
        open()
      }
      //改变页数限制
      const handleSizeChange = (e) => {
        xiangmuParams.size = e
        open()
      }
      let changeList = ref([])
      let activeName = ref('first')
      let isShow = ref(false)
      let isProject = ref(false)
      let select1 = ref([]) //项目

      let handleSelectionChange1 = (val) => {
        select1.value = val
      }
      const toHandle1 = () => {
        if (select1.value.length != 1) {
          tips('请选择一项关联', 'warning')
          return
        } else {
          let obj = select1.value[0]
          // data.diaForm.projectId = (obj as any).id
          // data.diaForm.project = (obj as any).projectName
          data.diaForm.projectId = obj.id
          data.diaForm.project = obj.projectName
          Visible.value = false
        }
      }
      Api.getProjectList().then((res) => {
        // console.log('项目列表', res.data.data)
        options.projectList = res.data.data
      })


      // 规则校验
        let rules = reactive({
            title: [{ required: true, message: "请输入论文题目", trigger: "blur" }],
            magazineName: [{ required: true, message: "请输入刊期名称", trigger: "blur" }],
            magazineNo: [{ required: true, message: "请输入刊期号", trigger: "change" }],

            publicDate: [{ required: true, message: "请选择发表日期", trigger: "change" }],
            levelId: [{ required: true, message: "请选择论文级别", trigger: "change" }],

          projectName: [{ required: true, message: "请选择所属项目", trigger: "change" }],

            techClassId: [{ required: true, message: "请选择技术分类", trigger: "change" }],
            maintainUnit: [{ required: true, message: "请选择维护单位", trigger: "change" }],
            enterpriseRanking: [
                { required: true, message: "请选择企业排名", trigger: "change" },
            ],
          isContractSuccess: [
            { required: true, message: '请输入合同中规定的成果', trigger: 'change', },
          ],

            languageId: [{ required: true, message: "请选择语言", trigger: "change" }],

            wordCount: [{ required: true, message: "请输入字数", trigger: "change" }],
            yxyz: [{ required: true, message: "请输入数字（两位小数）", trigger: "change" }],
        });

        let changeUnitInfo = (params) => {
            data.unitFlag = false;

            data.unitList = params;
        };

        let changeUnit = (item) => {

            data.diaForm.maintainUnitId = item.id

            data.diaForm.maintainUnit = item.name
        }


        let changePeopleInfo = (params) => {

            data.memberFlag = false;

            data.memberList = params;

        }


        // 著作级别,编著属性,技术分类,语言,企业排名===>数据字典

        let getCodeList = () => {
            getDictionary([
                "KJSL_ACADEMIC_WORK_LEVEL",
                "KJSL_SOFT_STATE",
                "KJSL_BUSINESS_SECTOR",
                "KJSL_LANGUAGE",
                "KJSL_ENTERPRISE_RANKING",
                "KJSL_THESIS_LEVEL",
            ]).then((res) => {
                data.levelList = res.data.data.KJSL_THESIS_LEVEL;

                data.techClassList = res.data.data.KJSL_BUSINESS_SECTOR;

                data.languageList = res.data.data.KJSL_LANGUAGE;

                data.RankingList = res.data.data.KJSL_ENTERPRISE_RANKING;
            });
        };

        // 项目

        let getProjectList = () => {
            getProject({}).then((res) => {
                data.projectList = res.data.data;
            });
        };

        // 保存
        let save = () => {
            DiaForm.value.validate((valid) => {
                // 校验通过
                if (valid) {
                    //flag 1 新增  2 编辑  3  详情
                    if (props.flag == 1) {
                        data.diaForm.id = "";

                        addForm({
                            baseInfo: data.diaForm,
                            fileList: data.files,
                            memberList: data.memberList,

                            unitList: data.unitList,
                        }).then(() => {
                            tips("新增成功", "success");

                            DiaForm.value.resetFields();

                            emit("changeDialog", "1");
                        });
                    } else {
                        editForm({
                            baseInfo: data.diaForm,
                            fileList: data.files,
                            memberList: data.memberList,
                            unitList: data.unitList,
                        }).then(() => {
                            tips("编辑成功", "success");

                            DiaForm.value.resetFields();

                            emit("changeDialog", "1");
                        });
                    }
                } else {
                    return tips("请将基本信息补充完整", "warning");
                }
            });
        };

        let filesParams = (params) => {
            data.files = params;
        };

        // 单位
        let getUnitList = () => {
            getUnit({}).then((res) => {
                data.unitNameList = res.data.data;
            });
        };

        //论文级别

        let changeLevel = (id) => {
            let itemText = data.levelList.find((item) => item.itemValue == id).itemText;

            data.diaForm.level = itemText;
        };

        // 所属项目

        let changeProject = (id) => {
            let itemText = data.projectList.find((item) => item.id == id).projectname;

            data.diaForm.project = itemText;
        };

        // 技术分类

        let changeTechClass = (id) => {
            let itemText = data.techClassList.find((item) => item.itemValue == id).itemText;

            data.diaForm.techClass = itemText;
        };

        let changeLange = (id) => {
            let itemText = data.languageList.find((item) => item.itemValue == id).itemText;
            data.diaForm.language = itemText;
        };

        // 通过详情查询id

        let getDetail = async (id) => {
            data.detail_loading = true
            let res = await getDetailById(id);

            data.unitFlag = true;

            data.memberFlag = true;

            data.diaForm = res.data.data.info;

            data.files = res.data.data.files;

            data.unitList = res.data.data.unitList;

            data.memberList = res.data.data.memberList;

            data.changeLogs = res.data.data.changeLogs;
            data.detail_loading = false
        };

        // 关闭清除对话框里面的数据,附件.变更记录也要删除
        // tabId也要设置初始值,否则在电点击编辑record,新增打开会出现空白页

        let close = () => {
            data.tabId = "1";
            DiaForm.value.resetFields();
            emit("changeDialog");


        };

        return {
            deptForm,
            DiaForm,
            filesParams,
            rules,
            changePeopleInfo,
            changeUnitInfo,
            changeLevel,
            changeProject,
            changeTechClass,
            getUnitList,
            changeUnit,
            changeLange,
            getProjectList,
            getCodeList,
            ...toRefs(data),
            close,
            save,

            open,
            handleCurrentChange,
            handleSizeChange,
            toHandle1,
            Visible,
            handleSelectionChange1,
            changeList,
            activeName,
            isShow,
            isProject,
            xiangmuParams,
            options,
          clearForm,

    };
    },
};
</script>

<style scoped lang="scss">
.dialog-footer {
    display: flex;
    justify-content: end;
}

:deep(.el-dialog__body) {
    display: none;
}

// 滚动条
:deep(.demo-tabs > .el-tabs__content) {
    max-height: 500px;
    overflow-y: scroll;
    scrollbar-width: none;
    -ms-overflow-style: none;
}
</style>
